
"""
    Delete all meta files from the current choosen dir/files
"""

import os
import sys

import Tkinter as tk
import tkMessageBox
from tkFileDialog import askdirectory

from externals.pyconfig.pyconfig import PyConfig

import sharedTkinter
from defaultDialog import DefaultDialog



class BaseVirtualizeDialog(DefaultDialog):
    def __init__(self, parent, fs_items, cfg):
        self.fs_items = fs_items
        self.cfg = cfg
        DefaultDialog.__init__(self, parent)

    def setup_widgets(self):
        tk.Label(self, text=self.info_txt).pack()

        pathframe = tk.Frame(self)

        tk.Label(pathframe, text="Ouput path:").pack(side=tk.LEFT)
        # Create textfield
        self.textfield = tk.Text(
            pathframe, width = 79, height = 1
        )
        self.textfield.insert(tk.END, "Please select -->")
        self.textfield.config(state=tk.DISABLED)

        self.textfield.pack(side=tk.LEFT)

        self.out_path = None
        button = tk.Button(pathframe, text = "choose", command = self.choose_path)
        button.pack()

        pathframe.pack(fill=tk.X)

        old_path = self.cfg.get("old output path")
        if old_path:
            self._set_new_path(old_path)


    def _set_new_path(self, path):
        print "new output path: %r" % path
        self.out_path = path

        self.textfield.config(state=tk.NORMAL)
        self.textfield.delete(1.0, tk.END)
        self.textfield.insert(tk.END, path)
        self.textfield.config(state=tk.DISABLED)

    def choose_path(self, event=None, old_path=None):
        if old_path == None:
            initialdir = self.cfg.get("old output path", os.getcwd())
        else:
            initialdir = old_path

        path = askdirectory(
            mustexist=1,
            parent = self,
            title = 'Choose symlink Directory (must be empty!)',
            initialdir=initialdir,
        )
        if not path:
            return

        path = os.path.normpath(path)

        if self.out_path_must_empty == True:
            if os.listdir(path) != []:
                selection = tkMessageBox.askyesno(
                    title="retry?", message=(
                        "Info: The output path is not empty!\n\n"
                        "Use this path?"
                    )
                )
                if selection != True:
                    self.choose_path(old_path = path)
                    return

        self._set_new_path(path)
        self.cfg["old output path"] = self.out_path
        self.cfg.save()



class CreateVirtualizeDialog(BaseVirtualizeDialog):
    info_txt = "Create virtualize directory"
    out_path_must_empty = True

    def setup_widgets(self):
        BaseVirtualizeDialog.setup_widgets(self)

        # Create a ScrolledText and insert all fs_items
        sharedTkinter.add_fs_items(self, self.fs_items)

        self.meta_select_list = sharedTkinter.meta_key_select(
            self, self.fs_items
        )

        # Create Buttons
        buttonframe = tk.Frame(self)

        button = tk.Button(buttonframe, text = "create", command = self.create)
        button.pack(side=tk.LEFT)

        button = tk.Button(buttonframe, text = "cancel", command = self.destroy)
        button.pack(side=tk.LEFT)

        buttonframe.pack(fill=tk.X)

    def create(self):

        if self.out_path == None:
            tkMessageBox.showerror(message="Error: No output path selected!")
            return

        existing_items = self.meta_select_list.get(0, tk.END)
        selection = []
        for i in self.meta_select_list.curselection():
            index = int(i) # i ist ein String
            selection.append(existing_items[index])

        print selection

        if selection == []:
            tkMessageBox.showerror(message="Error: No meta type selected!")
            return

        for fs_item in self.fs_items:
            print " -"*40
            print fs_item
            meta = fs_item.meta
            for key in selection:
                for txt in meta[key]:
                    fs_item.virtualize(
                        outpath = os.path.join(self.out_path, txt)
                    )


class DeleteVirtualizeDialog(BaseVirtualizeDialog):
    info_txt = "Delete virtualize directory"
    out_path_must_empty = False

    def setup_widgets(self):
        BaseVirtualizeDialog.setup_widgets(self)

        # Create Buttons
        buttonframe = tk.Frame(self)

        button = tk.Button(buttonframe, text = "delete", command = self.delete)
        button.pack(side=tk.LEFT)

        button = tk.Button(buttonframe, text = "cancel", command = self.destroy)
        button.pack(side=tk.LEFT)

        buttonframe.pack(fill=tk.X)

    def delete(self, path=None):
        if path==None:
            path = self.out_path
            
        print "delete:", path
        
        diritems = os.listdir(path)
        if diritems == [] and path != self.out_path:
            print "rmdir:", path
            os.rmdir(path)
            return
        
        for diritem in diritems:
            abs_path = os.path.join(path, diritem)
            if os.path.isdir(abs_path):
                self.delete(abs_path)
            else:
                # Check if hardlink?
                print "delete file:", abs_path,
                try:
                    os.remove(abs_path)
                except Exception, err:
                    print "Error:", err
                else:
                    print "OK"
                




if __name__ == '__main__':
    #test the dialog
    
    os.chdir("..") # go into root
    sys.path.insert(0, os.getcwd())
    
    
    from simpledms import CONFIG_PATH, DEFAULT_CONFIG
    from main import FilesystemItem
    
    
    cfg = PyConfig(filename=CONFIG_PATH, verbose=1, defaults=DEFAULT_CONFIG)
    
    
    fs_items = []
    path = "example"
    for filename in os.listdir(path):
        abspath = os.path.join(path, filename)
        try:
            item = FilesystemItem.FilesystemItem(abspath)
        except FilesystemItem.FilesystemItemError:
            continue
        fs_items.append(item)
    
    
    root=tk.Tk()
    tk.Label(root, text="Test Tkinter root\n", width=30).pack()
    tk.Button(
        root, text='CreateVirtualizeDialog',
        command=lambda:CreateVirtualizeDialog(root, fs_items, cfg)
    ).pack()
    
    tk.Button(
        root, text='DeleteVirtualizeDialog',
        command=lambda:DeleteVirtualizeDialog(root, fs_items, cfg)
    ).pack()
    
    
    root.mainloop()